package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.vo.ResourceVO;
import csu.web.credit_bank.service.UserResourceService;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/user-resources")
@CrossOrigin
public class UserResourceController {

    @Autowired
    private UserResourceService userResourceService;

    // 用户加入（购买）一个资源
    @PostMapping("/join")
    public Result<Void> joinResource(@RequestBody Map<String, String> payload) {
        String userId = payload.get("userId");
        String resourceId = payload.get("resourceId");

        if (userId == null || resourceId == null) {
            return Result.failure("用户ID和资源ID不能为空");
        }

        try {
            userResourceService.joinResource(userId, resourceId);
            return Result.success("资源加入成功");
        } catch (IllegalStateException e) {
            return Result.failure(e.getMessage());
        } catch (Exception e) {
            return Result.failure("加入资源失败，请稍后重试");
        }
    }

    // 获取用户加入的所有资源列表（分页）
    @GetMapping("/joined/{userId}")
    public Result<IPage<ResourceVO>> getJoinedResources(
            @PathVariable String userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size
    ) {
        Page<ResourceVO> pageInfo = new Page<>(page, size);
        IPage<ResourceVO> results = userResourceService.getJoinedResources(userId, pageInfo);
        return Result.success(results);
    }

    // 检查用户对一批资源的所有权状态
    @PostMapping("/check-ownership")
    public Result<Set<String>> checkOwnership(@RequestBody Map<String, Object> payload) {
        String userId = (String) payload.get("userId");
        // Spring MVC/Jackson 默认会将JSON数组反序列化为ArrayList
        @SuppressWarnings("unchecked")
        List<String> resourceIds = (List<String>) payload.get("resourceIds");

        if (userId == null || resourceIds == null || resourceIds.isEmpty()) {
            return Result.failure("用户ID和资源ID列表不能为空");
        }

        try {
            Set<String> ownedIds = userResourceService.getOwnedResourceIds(userId, resourceIds);
            return Result.success(ownedIds);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常方便调试
            return Result.failure("检查资源所有权失败");
        }
    }
}